#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TMDb电影刮削器 - 一键打包EXE脚本
自动安装依赖并使用PyInstaller打包成可执行文件
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path

def run_command(command, description=""):
    """执行命令并显示输出"""
    print(f"\n{'='*60}")
    print(f"🔧 {description}")
    print(f"{'='*60}")
    print(f"执行命令: {command}")
    print("-" * 60)
    
    try:
        result = subprocess.run(command, shell=True, check=True, 
                              capture_output=False, text=True)
        print(f"✅ {description} 完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ {description} 失败: {e}")
        return False

def check_python():
    """检查Python版本"""
    print("🐍 检查Python环境...")
    version = sys.version_info
    print(f"Python版本: {version.major}.{version.minor}.{version.micro}")
    
    if version.major < 3 or (version.major == 3 and version.minor < 7):
        print("❌ 需要Python 3.7或更高版本")
        return False
    
    print("✅ Python版本符合要求")
    return True

def install_dependencies():
    """安装依赖包"""
    print("\n📦 安装依赖包...")
    
    # 检查是否存在requirements.txt
    if not os.path.exists("requirements.txt"):
        print("❌ 未找到requirements.txt文件")
        return False
    
    # 升级pip
    if not run_command(f"{sys.executable} -m pip install --upgrade pip", "升级pip"):
        return False
    
    # 安装依赖
    if not run_command(f"{sys.executable} -m pip install -r requirements.txt", "安装项目依赖"):
        return False
    
    return True

def create_spec_file():
    """创建PyInstaller配置文件"""
    print("\n📝 创建PyInstaller配置文件...")
    
    spec_content = '''# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(
    ['main.py'],
    pathex=[],
    binaries=[],
    datas=[
        ('help.txt', '.')
    ],
    hiddenimports=[
        'tkinter',
        'tkinter.ttk',
        'tkinter.filedialog',
        'tkinter.messagebox',
        'tkinter.scrolledtext',
        'requests',
        'bs4',
        'urllib.parse',
        'queue',
        'threading',
        'webbrowser',
        'shutil',
    ],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

splash = Splash(
    'splash.png',
    binaries=a.binaries,
    datas=a.datas,
    text_pos=None,
    text_size=12,
    minify_script=True,
    always_on_top=True,
)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    splash,
    [],
    name='TMDb电影刮削器',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=False,  # 设置为False隐藏控制台窗口
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    icon='icon.ico',  # 可以添加图标文件路径
)
'''
    
    try:
        with open("tmdb_scraper.spec", "w", encoding="utf-8") as f:
            f.write(spec_content)
        print("✅ 配置文件创建成功: tmdb_scraper.spec")
        return True
    except Exception as e:
        print(f"❌ 创建配置文件失败: {e}")
        return False

def build_exe():
    """使用PyInstaller打包EXE"""
    print("\n🔨 开始打包EXE文件...")
    
    # 清理之前的构建文件
    for folder in ["build", "dist"]:
        if os.path.exists(folder):
            print(f"🧹 清理旧的{folder}文件夹...")
            shutil.rmtree(folder)
    
    # 使用spec文件打包
    if not run_command("pyinstaller tmdb_scraper.spec", "PyInstaller打包"):
        return False
    
    return True

def post_build_cleanup():
    """构建后清理"""
    print("\n🧹 清理临时文件...")
    
    # 清理构建文件夹
    if os.path.exists("build"):
        shutil.rmtree("build")
        print("✅ 清理build文件夹")
    
    # 清理spec文件
    if os.path.exists("tmdb_scraper.spec"):
        os.remove("tmdb_scraper.spec")
        print("✅ 清理spec文件")
    
    print("✅ 清理完成")
    return True


def main():
    """主函数"""
    print("🎬 TMDb电影刮削器 - 一键打包EXE工具")
    print("=" * 60)
    
    # 检查当前目录是否包含必要文件
    required_files = ["main.py", "modules/gui.py", "modules/scrapers.py"]
    missing_files = [f for f in required_files if not os.path.exists(f)]
    
    if missing_files:
        print(f"❌ 缺少必要文件: {', '.join(missing_files)}")
        print("请确保在项目根目录下运行此脚本")
        return False
    
    # 执行构建步骤
    steps = [
        (check_python, "检查Python环境"),
        (install_dependencies, "安装依赖包"),
        (create_spec_file, "创建配置文件"),
        (build_exe, "打包EXE文件"),
        (post_build_cleanup, "清理临时文件"),
    ]
    
    for step_func, step_name in steps:
        if not step_func():
            print(f"\n❌ {step_name}失败，构建中止")
            return False
    
    # 检查输出文件
    exe_path = os.path.join("dist", "TMDb电影刮削器.exe")
    if os.path.exists(exe_path):
        file_size = os.path.getsize(exe_path) / (1024 * 1024)  # MB
        print(f"\n🎉 打包成功!")
        print(f"📁 输出文件: {exe_path}")
        print(f"📊 文件大小: {file_size:.1f} MB")
        print(f"\n💡 使用说明:")
        print(f"   - 双击运行EXE文件启动GUI界面")
        print(f"   - 或在命令行中使用: \"TMDb电影刮削器.exe\" <电影文件夹路径>")
        print(f"   - 可以将EXE文件复制到任何位置使用")
        return True
    else:
        print(f"\n❌ 未找到输出文件: {exe_path}")
        return False

if __name__ == "__main__":
    try:
        success = main()
        if not success:
            input("\n按回车键退出...")
            sys.exit(1)
        else:
            input("\n按回车键退出...")
    except KeyboardInterrupt:
        print("\n\n⚠️ 用户中断操作")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ 发生未预期的错误: {e}")
        input("\n按回车键退出...")
        sys.exit(1)
